'use client'
import './index.scss'
import React, { useState, useEffect } from "react"
import { GetWord, ParseWord, StopParseWord, DownloadWord } from '@/app/api/RAGflow/index'
import keyStore from '@/app/store/key'
import { Button, Input, Table, Tag, message, Pagination } from 'antd'
import { PlusOutlined, SearchOutlined, DeleteOutlined, EditOutlined, VerticalAlignBottomOutlined, RetweetOutlined, PlayCircleOutlined, PauseCircleOutlined, RedoOutlined } from '@ant-design/icons';
import ModalUI from './Modalui/page'
import Chunk from './Chunk/page'



interface DocumentsProps {
    id: string
}


const getDate = (dateString: string) => {
    const date = new Date(dateString);
    const year = date.getUTCFullYear();
    const month = String(date.getUTCMonth() + 1).padStart(2, '0');
    const day = String(date.getUTCDate()).padStart(2, '0');
    const hours = String(date.getUTCHours()).padStart(2, '0');
    const minutes = String(date.getUTCMinutes()).padStart(2, '0');
    const seconds = String(date.getUTCSeconds()).padStart(2, '0');
    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    return formattedDate;
}


const Documents: React.FC<DocumentsProps> = ({ id }) => {
    const { RAGFlowKey } = keyStore()
    const [documents, setDocuments] = useState<any[]>([]);
    const [copydoc, setcopudoc] = useState<any[]>([])
    const [open, setopen] = useState<boolean>(false)
    const [isword, setisword] = useState<boolean>(true)
    const [queryvalue, setqueryvalue] = useState<string>('')
    const [type, settype] = useState<string>('')
    const [data, setdata] = useState<any>({})
    const [chunk, setchunk] = useState({})
    const [current, setCurrent] = useState(1); // 当前页码
    const [pageSize, setPageSize] = useState(5); // 每页显示条数
    const [total, setTotal] = useState(0); // 数据总数


    const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);

    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '分块数',
            dataIndex: 'chunk_count',
            key: 'chunk_count'
        },
        {
            title: '上传时间',
            dataIndex: 'create_date',
            key: 'create_date',
            render: (value: string) => {
                return <div>
                    {getDate(value)}
                </div>
            }
        },
        {
            title: '更新时间',
            dataIndex: 'update_date',
            key: 'update_date',
            render: (value: string) => {
                return <div>
                    {getDate(value)}
                </div>
            }
        },
        {
            title: '解析状态',
            dataIndex: 'progress',
            key: 'progress',
            render: (value: any) => {
                return <div className='tag'>
                    {value == 0 && <Tag color="cyan">未解析</Tag>}
                    {value == 1 && <Tag color="geekblue">解析成功</Tag>}
                    {value == -1 && <Tag color="red">解析失败</Tag>}
                    {value !== 0 && value !== 1 && value != -1 && <Tag color="blue">解析中 {(value * 100).toFixed(2)}% </Tag>}
                </div>
            }
        },
        {
            title: '操作',
            render: (value: any) => {
                return <div className='table' onClick={(e) => { e.stopPropagation() }}>

                    {value.progress == 0 && <span onClick={() => {
                        FCParseWord([value.id])
                    }}><PlayCircleOutlined /></span>}

                    {value.progress != 0 && value.progress < 1 && value.progress != -1 && <span onClick={() => {
                        StopParseWord(value.dataset_id, [value.id], RAGFlowKey).then((res: any) => {
                            if (res.code == 0) {
                                message.success('停止解析')
                                getlist()
                            } else {
                                message.error(res.msg)
                            }
                        })
                    }}><PauseCircleOutlined /></span>}


                    <span onClick={() => { settype('edit'); setdata(value); setopen(true); console.log(value, 99) }}><EditOutlined /></span>
                    <span onClick={() => {
                        DownloadWord(value.dataset_id, value.id, RAGFlowKey).then((response: any) => {
                            const urlObject = window.URL.createObjectURL(response);
                            const link = document.createElement('a');
                            link.href = urlObject;
                            let fileName = value.name;
                            link.download = fileName;
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                            window.URL.revokeObjectURL(urlObject);
                        })
                    }}><VerticalAlignBottomOutlined /> </span>
                    <a className='delete' onClick={() => { settype('del'); setdata(value); setopen(true) }}><DeleteOutlined /> </a>
                </div>
            }
        },
    ];

    useEffect(() => {
        getlist()
        const intervalId = setInterval(() => {
            getlist();
        }, 10000);

        return () => clearInterval(intervalId);
    }, [id, current, pageSize])

    const getlist = () => {
        GetWord(id, current, pageSize, queryvalue, '', RAGFlowKey).then((res: any) => {
            const docsWithKey = res.data.docs.map((doc: any) => ({
                ...doc,
                key: doc.id,
            }));
            setDocuments(docsWithKey);
            setcopudoc(docsWithKey);
            setTotal(res.data.total);
        });
    };

    const FCParseWord = (idlist: any[]) => {
        ParseWord(id, idlist, RAGFlowKey).then((res: any) => {
            if (res.code === 0) {
                message.success('正在解析');
                setSelectedRowKeys([])
                getlist();
            } else {
                message.error(res.message);
            }
        });
    }

    const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            getlist()
        }
    };

    const handlePageChange = (page: number, pageSize?: number) => {
        setCurrent(page);
        if (pageSize) {
            setPageSize(pageSize);
        }
    };

    const onSelectChange = (newSelectedRowKeys: any) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
        getCheckboxProps: (record: any) => ({
            disabled: record.progress !== 0, // 当 progress 不等于 0 时禁用复选框
        }),
    };

    const onRow = (record: any) => {
        return {
            onClick: () => {
                setisword(false)
                setchunk(record)
            }
        }
    }
    return (
        <div className="documents">
            <div className='documentcontent'>

                {
                    isword ? <>
                        <div className='documents_title'>
                            <Input size="large" style={{ height: '32px', width: '200px' }} placeholder="搜索" prefix={<SearchOutlined />} onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                                setqueryvalue(e.target.value)
                            }} onKeyDown={handleKeyPress} />
                            <div>
                                <Button icon={<RedoOutlined />} style={{ marginLeft: '10px' }} onClick={() => { getlist(); message.success('刷新成功') }} />
                                <Button type="primary" icon={<PlusOutlined />} style={{ margin: '0px 10px' }} onClick={() => { setopen(true); settype('file') }}>添加文件</Button>
                                {selectedRowKeys.length != 0 && <Button
                                    type="primary"
                                    icon={<PlayCircleOutlined />}
                                    onClick={() => { FCParseWord(selectedRowKeys) }}
                                >批量解析
                                </Button>}
                            </div>
                        </div>
                        <div>
                            <Table columns={columns} dataSource={documents} pagination={false} className='tablelist' rowSelection={rowSelection} onRow={(record) => onRow(record)} />
                            <div className='pagination'>
                                <Pagination
                                    current={current}
                                    pageSize={pageSize}
                                    total={total}
                                    showTotal={(total) => `共 ${total} 条`}
                                    onChange={handlePageChange}
                                    showSizeChanger
                                    pageSizeOptions={[5, 10, 30, 50, 100]} //
                                />
                            </div>
                        </div>
                    </> : <Chunk data={chunk} setDate={(value) => { setisword(value) }} />
                }


                <ModalUI
                    open={open}
                    setData={(value: boolean) => { setopen(value); getlist() }}
                    id={id}
                    type={type}
                    data={data} />
            </div>
        </div>
    )
}

export default Documents